import { createWebHistory, createRouter } from "vue-router";
import useUserStore from '@/store/index.js'
import { storeToRefs } from 'pinia';
import axios from 'axios'
const routes = [
    //后台路由
    { path: '/', redirect: '/login' },
    { path: '/login', name: "login", meta: { title: "管理员登录" }, 
     component: () => import('@/pages/login.vue') },
     { path: '/home', name: "home", meta: { title: "后台管理系统" }, 
     component: () => import('@/pages/home.vue'),
     children: [
        { path: "/home", redirect: "/home/jobs" },
        { path: "jobs", name: "jobs",  meta: { title: "岗位管理" }, 
         component: () => import('@/pages/jobs.vue') },
         { path: 'jobDetail/:id?', name: "jobDetail",  meta: { title: "岗位详情" },
         component: () => import('@/pages/jobDetail.vue') }, 
        { path: "notice", name: "notice",  meta: { title: "通知公告管理" }, 
         component: () => import('@/pages/notice.vue') },
        { path: "users", name: "users",  meta: { title: "用户管理" }, 
         component: () => import('@/pages/users.vue') },
        { path: "databoard", name: "databoard",  meta: { title: "数据看板" }, 
         component: () => import('@/pages/dataBoard.vue') },
    ]
    },
     { path: '/404', name: "404",  meta: { title: "未找到该页面" },
     component: () => import('@/pages/404.vue')},
     { path: '/:pathMatch(.*)*', redirect: "/404"},
]
const router = createRouter({
    history: createWebHistory(),
    routes: routes
});
/* 全局路由守卫进行登录状态判断 */
router.beforeEach((to, from, next) => {
    const store = useUserStore();
    const { username, token } = storeToRefs(store)
    if (to.meta.title) {
        document.title = to.meta.title
    }
    if (to.path == '/login') {
        return next();
    }
    if (token.value) {
        axios.defaults.headers['Authorization'] = `Bearer ${token.value}`;
        return next()
    }
    else {
        return next('/login');
    }
})

export default router